package cn.itsource.zcn.order.service.impl;

import cn.itsource.zcn.alipay.domain.PayAlipayInfo;
import cn.itsource.zcn.alipay.mapper.PayAlipayInfoMapper;
import cn.itsource.zcn.alipay.service.AliPayService;
import cn.itsource.zcn.order.domain.OrderAddress;
import cn.itsource.zcn.order.domain.OrderAdopt;
import cn.itsource.zcn.order.mapper.OrderAddressMapper;
import cn.itsource.zcn.order.mapper.OrderAdoptMapper;
import cn.itsource.zcn.order.service.IOrderAdoptService;
import cn.itsource.zcn.pay.domain.PayBill;
import cn.itsource.zcn.pay.mapper.PayBillMapper;
import cn.itsource.zcn.pet.domain.Pet;
import cn.itsource.zcn.pet.mapper.PetMapper;
import cn.itsource.zcn.quartz.domain.QuartzJobInfo;
import cn.itsource.zcn.quartz.service.MyJob;
import cn.itsource.zcn.quartz.util.QuartzUtils;
import cn.itsource.zcn.user.domain.Logininfo;
import cn.itsource.zcn.user.domain.User;
import cn.itsource.zcn.user.domain.UserAddress;
import cn.itsource.zcn.user.mapper.UserAddressMapper;
import cn.itsource.zcn.user.mapper.UserMapper;
import cn.itsource.zcn.utils.CodeGenerateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (OrderAdopt)表服务实现类
 *
 * @author makejava
 * @since 2021-08-26 11:07:38
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class OrderAdoptServiceImpl implements IOrderAdoptService {
    @Autowired
    private OrderAdoptMapper tOrderAdoptMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private PayAlipayInfoMapper payAlipayInfoMapper;

    @Autowired
    private SchedulerFactoryBean schedulerFactortBean;
    /**
     * 新增数据
     *
     * @param tOrderAdopt 实例对象
     */
    @Override
    @Transactional
    public void save(OrderAdopt tOrderAdopt) {
        tOrderAdoptMapper.save(tOrderAdopt);
    }

    /**
     * 修改数据
     *
     * @param tOrderAdopt 实例对象
     */
    @Override
    @Transactional
    public void update(OrderAdopt tOrderAdopt) {
        tOrderAdoptMapper.update(tOrderAdopt);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     */
    @Override
    @Transactional
    public void delete(Long id) {
        tOrderAdoptMapper.delete(id);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrderAdopt queryById(Long id) {
        return tOrderAdoptMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<OrderAdopt> queryAll() {
        return tOrderAdoptMapper.queryAll();
    }

    /**
     * 用户提交订单
     * @param map
     */
    @Override
    @Transactional
    public String submitOrder(Map<String, String> map, HttpServletRequest request) {
        // 拿去前端数据
        /*
        address_id: 1,
        payType: "AliPay",
        //选中的服务
        pet_id:0
         */
        Long address_id = Long.valueOf(map.get("address_id"));
        String payType = map.get("payType");
        Long pet_id = Long.valueOf(map.get("pet_id"));

        //获取当前登录用户
        // 拿出当前登录用户
        String token = request.getHeader("token");
        Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
        User user = userMapper.queryById(logininfo.getUid());

        //1.下架宠物
        Pet pet = petMapper.queryById(pet_id);
        //设置状态为0
        pet.setState(0L);
        // 设置下架时间
        pet.setOffsaletime(new Date());
        // 修改pet(下架)
        petMapper.update(pet);

        //2.创建订单
        OrderAdopt orderAdopt = createOrderAdopt(pet,user);
        tOrderAdoptMapper.save(orderAdopt);

        //3.创建地址
        OrderAddress orderAddress = createOrderAddress(orderAdopt,address_id);
        orderAddressMapper.save(orderAddress);

        //4.生成支付账单
        PayBill payBill = createPayBill(orderAdopt,payType);
        payBill.setBusinessType("AliPay");
        payBillMapper.save(payBill);

        //添加定时器
        HashMap<String, Object> params = new HashMap<>();
        params.put("orderSn",payBill.getOrderSn());
        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        quartzJobInfo.setFireDate(payBill.getLastPayTime());
        //添加定时任务
        QuartzUtils.addJob(schedulerFactortBean.getScheduler(),payBill.getOrderSn()
        , MyJob.class,params,quartzJobInfo.getCronj());

        //5.调用支付接口，跳转支付页面
        PayAlipayInfo payAlipayInfo = payAlipayInfoMapper.queryById(1L);
        String result = aliPayService.pay(payBill,payAlipayInfo);
        return result;
    }

    private PayBill createPayBill(OrderAdopt orderAdopt,String pay) {
        PayBill payBill = new PayBill();
        BeanUtils.copyProperties(orderAdopt,payBill);
        payBill.setMoney(orderAdopt.getPrice());
        payBill.setPayChannel(pay);
        payBill.setCreateTime(new Date());
        payBill.setOrder_id(orderAdopt.getId());
        return payBill;
    }

    private OrderAddress createOrderAddress(OrderAdopt orderAdopt,Long address_id) {
        //根据address_id查询出地址数据
        UserAddress userAddress = userAddressMapper.queryById(address_id);
        OrderAddress orderAddress = new OrderAddress();
        // 将数据复制到orderAddress中
        BeanUtils.copyProperties(userAddress,orderAddress);
        // 设置order里面参数
        orderAddress.setOrder_id(orderAdopt.getId());
        orderAddress.setOrderSn(orderAdopt.getOrderSn());
        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }

    private OrderAdopt createOrderAdopt(Pet pet, User user) {
        OrderAdopt orderAdopt = new OrderAdopt();
        orderAdopt.setDigest("[领养订单]");//设置订单类型
        orderAdopt.setState(0);//待支付状态
        orderAdopt.setPrice(pet.getSaleprice());//订单价格
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        orderAdopt.setOrderSn(orderSn);//订单编号
        orderAdopt.setLastPayTime(new Date(System.currentTimeMillis()+15*60*1000));  //最后支付时间
        orderAdopt.setPet_id(pet.getId());//设置宠物编号
        orderAdopt.setUser_id(user.getId());//设置用户编号
        orderAdopt.setShop_id(pet.getShop_id()); //设置店铺id
        return orderAdopt;
    }


}
